import QtQuick
import QtQuick.Controls
import "qrc:/qml/styles" as Styles

Rectangle {
    id: toast

    property string type: "info" // info / success / error / warning
    property int duration: 3000
    property bool autoHide: true
    property alias text: messageLabel.text

    radius: Styles.Theme.radiusNormal
    color: type === "success" ? Styles.Theme.success
          : type === "error" ? Styles.Theme.danger
          : type === "warning" ? Styles.Theme.warning
          : Styles.Theme.info
    opacity: 0
    visible: opacity > 0
    z: 999

    implicitWidth: messageLabel.implicitWidth + 2 * Styles.Theme.spacingLarge
    implicitHeight: messageLabel.implicitHeight + 2 * Styles.Theme.spacingSmall

    Behavior on opacity {
        NumberAnimation { duration: Styles.Theme.animationFast }
    }

    Row {
        anchors.fill: parent
        anchors.margins: Styles.Theme.spacingSmall
        spacing: Styles.Theme.spacingSmall

        Text {
            anchors.verticalCenter: parent.verticalCenter
            text: type === "success" ? "✔"
                 : type === "error" ? "⚠"
                 : type === "warning" ? "!"
                 : "ℹ"
            font.pixelSize: Styles.Theme.fontSizeMedium
            color: Styles.Theme.textOnPrimary
        }

        Text {
            id: messageLabel
            anchors.verticalCenter: parent.verticalCenter
            font.pixelSize: Styles.Theme.fontSizeNormal
            color: Styles.Theme.textOnPrimary
            wrapMode: Text.WrapAnywhere
        }
    }

    Timer {
        id: hideTimer
        interval: duration
        onTriggered: toast.hide()
    }

    function show(message, toastType) {
        if (message === undefined || message === null) {
            return;
        }
        messageLabel.text = message;
        if (toastType) {
            type = toastType;
        }
        opacity = 1;
        if (autoHide) {
            hideTimer.restart();
        }
    }

    function hide() {
        hideTimer.stop();
        opacity = 0;
    }
}
